<?php

/*
 * 1 - User can edit self profile
 * 2 - Add or Update User profile
 * 3 - Check login by AJAX
 * 4 - Turn User On
 * 5 - Turn User Off
 * 6 - Delete User(s)
 * 11 - Add or Update group
 * 12 - Delete Group(s)
 */

$USERS = new users();

# Force user to edit own profile
if (session::user() && !session::user()->hasRole('ADMIN') && session::user()->id != 1)
   $action = 1;

$data = array();

$SMARTY->assign('action', $action);


switch ($action)
{
   # USER CAN EDIT SELF PROFILE
   case 1:
      $DataObject = session::user();

      if (!empty($_POST['f']) && is_array($_POST['f']))
      {
         $DataObject->save($_POST['f']);
      }

      if (!empty($_POST['p']) && !empty($_POST['p']['oldpwd']) && !empty($_POST['p']['pwd']))
      {
         if ($DataObject->changePassword($_POST['p']['oldpwd'], $_POST['p']['pwd']))
         {
            session::logout();
            session::redirect();
         }
      }

      $SMARTY->assign('DataObject', $DataObject);
      $layout = 'user.html';
      break;



   # ADD OR UPDATE USER PROFILE
   // TODO: когда переработается аплоадер изображений - добавить функционал загрузки аватара пользователя. Это же в персональном редактировании профиля
   case 2:
      $data['user']   = new user($id);
   
      if (!empty($_POST['f']) && is_array($_POST['f']))
      {
         $data['user']->save($_POST['f']);
         $action = FALSE;

         # UPDATE USER'S GROUPS
         if(!empty($_POST['f']['group']))
         {
            $data['user']->setGroups($_POST['f']['group']);
         }
      }
      if (!empty($_POST['p']) && !empty($_POST['p']['pwd']))
      {
         # CHANGE USER PASSWORD
         $data['user']->changePassword(TRUE, $_POST['p']['pwd']);
         $action = FALSE;
      }

      if ($action)
      {
         
         $data['groups'] = $USERS->getGroups();

         $SMARTY->assign('data', $data);

         $layout = 'servlet.users.html';
      }
      break;



   # CHECK LOGIN BY AJAX
   case 3:
      $respond = TRUE;
      if (!empty($_GET['f']) && !empty($_GET['f']['login']))
      {
         $DB->DB_QueryBuilder('SELECT COUNT(*) FROM `meccano_users` WHERE `login`="%s"', array($_GET['f']['login']));
         $DB->DB_Query();
         if ($DB->DB_GetResult() != 0)
            $respond = FALSE;
      }

      echo json_encode($respond);
      exit();
      break;


   # TURN USER ON USING AJAX
   case 4:
      $respond = FALSE;
      if ($id)
         $respond = $USERS->turnOnUser($id);
      echo json_encode($respond);
      exit();
      break;



   # TURN USER OFF USING AJAX
   case 5:
      $respond = FALSE;
      if ($id)
         $respond = $USERS->turnOffUser($id);
      echo json_encode($respond);
      exit();
      break;



   # DELETE USER(S)
   case 6:
      if (!empty($_POST['delu']))
      {
         $USERS->deleteUser($_POST['delu']);
      }
      $action = FALSE;
      break;



   # EDIT OR ADD GROUP;
   case 11:
      if(!empty($_POST['f']) && is_array($_POST['f']))
      {
         if($id)
         {
            $USERS->updateGroup($id, $_POST['f']);
         } else
         {
            $USERS->addGroup($_POST['f']);
         }
         $action = FALSE;
      }

      if($action)
      {
         $data = array();
         if($id)
         {
            $data['group'] = $USERS->getGroup($id);
         }
         $data['roles'] = $USERS->getRoles();

         $SMARTY->assign('data', $data);
         $layout = 'servlet.users.html';
      }
      break;




   # DELETE GROUP(S)
   case 12:
      if (!empty($_POST['delg']))
      {
         $USERS->deleteGroup($_POST['delg']);
      }
      $action = FALSE;
      break;
}


# INIT SHOW LIST OF USERS AND GROUPS IF $ACTION IS UNSETED
if (!$action && !$ErrorHandler->getSuccess() && !$ErrorHandler->getErrorStatus())
{
   $filter = array();
   if(!empty($_POST['s']))
   {
      if(!empty($_POST['s']['login']))
         $filter['u']['login'] = $_POST['s']['login'];
      if(!empty($_POST['s']['email']))
         $filter['u']['email'] = $_POST['s']['email'];
      if(!empty($_POST['s']['group']))
         $filter['g']['gid'] = (count($_POST['s']['group']) == 1 ? reset($_POST['s']['group']) : $_POST['s']['group']);

      $SMARTY->assign('search', $_POST['s']);
   }
   $data['users'] = $USERS->getUsers($filter);
   $data['groups'] = $USERS->getGroups();

   $current_tab = !empty($_POST['tab']) && $FILTER->isValidInteger($_POST['tab']) ? $_POST['tab'] : 0;
   $SMARTY->assign('current_tab', $current_tab);
   $SMARTY->assign('data', $data);

   $layout = 'users.html';
}